#include "fig_mainmenu.h"
#include "fig_moving_particles.h"
#include "fighter.h"
#include "fig_vars.h"
#include "fig_constants.h"
#include "fig_sounds.h"
#include "fig_gamecenter.h"
#include "fig_sfx_manager.h"
#include "fig_vars.h"
#include "fig_app.h"
#include "fig_ios_wrapper.h"
#include "fig_ui_popupmanager.h"
#include "build.h"
#include "fig_bonefile_cache.h"
#include "mat_ui_animator.h"
#include "ui/ui_flexeffect.h"

#include "num/rand.h"
#include "dd/dd_man.h"
#include "ui/ui_manager.h"
#include "gameflow/game_flow_manager.h"
#include "gameflow/ui_popup.h"
#include "script/scripthelper.h"

#include "font/font_manager.h"

			// log
#include "resman/resman.h"				// log

#include "util/timer.h"				
#include "util/log.h"				// log
#include "util/common_macros.h"		// macros
#include "util/mmgr.h"

#ifdef _PLATFORM_ANDROID
#include "SDL2/src/core/android/SDL_android.h"
#include "android/sleipner_android.h"
#endif


#ifdef _ENABLE_LUABIND
#include <luabind/luabind.hpp>
#endif

#include <cassert>

using namespace script;

static FIGBoneAnimation* BoneAnimation = NULL;

bool	RenderAnimation(bool b)
{
	if(BoneAnimation)
	{
		BoneAnimation->Render(math::Vec2(0.0f,0.0f),1.0f);
	}

	return true;
}

FIGMainMenu::FIGMainMenu(camera::FbCamera*	pCamera ) :
												FIGMOGAUIState(pCamera, "ui/main_menu.ui"),
												m_IsFinishTitleAnimation(false),
												m_pUI(NULL)
{	
	BoneAnimation = &m_BoneTitle;

#ifndef _PLATFORM_IOS
	AddToNaviationUI(GetWidget("START_GAME"));
	AddToNaviationUI(GetWidget("SETTINGS_2"));
	AddToNaviationUI(GetWidget("button_highscore"));
	AddToNaviationUI(GetWidget("button_achievements"));
#endif

	

	SetMusic(FIGSounds::MUSIC_MENU);
	SetupTransition("START_GAME", "level_select");
	SetWidgetFunctor("SETTINGS_2",UI_DELEGATE(FIGMainMenu, OnButtonSettings));
	SetWidgetFunctor("BUTTON_HIGHSCORE",UI_DELEGATE(FIGMainMenu, OnButtonLeaderBoard));
	SetWidgetFunctor("button_achievements",UI_DELEGATE(FIGMainMenu, OnButtonAchievements)); 
	

	//m_MainSpaceBG.Create("space_background_1");

	if(GetWidget("button_achievements"))
        GetWidget("button_achievements")->SetIsVisible(false);

//#ifdef _PLATFORM_ANDROID
	if(GetWidget("BUTTON_HIGHSCORE"))
	{
		// http://list.mobappbox.com/android?language=en&tag=mobappbox
		GetWidget("BUTTON_HIGHSCORE")->SetTextA("More Games");
	}

	if(GetWidget("button_achievements"))
	{
	    GetWidget("button_achievements")->SetIsVisible(true);
	    GetWidget("button_achievements")->SetTextA("Rate Us");
	}

	/*
	if(GetWidget("START_GAME"))
	{
		GetWidget("START_GAME")->SetPosition(GetWidget("START_GAME")->GetPosition() + math::Vec2(0,0.07f));
		GetWidget("START_GAME")->SetTextColor(0.1f ,0.2f ,0.1f ,1.0f);
	}

	if(GetWidget("SETTINGS"))
	{
		GetWidget("SETTINGS")->SetPosition(GetWidget("SETTINGS")->GetPosition() + math::Vec2(0,0.1f));
		
	}
	*/
	 

	std::string Language = FIGVars::Instance()->GetLanguage();
	if(Language.compare("CHINESE") == 0 ||
		Language.compare("KOREAN") == 0 ||
		Language.compare("JAPANESE") == 0 )
	{
		//FIGApp::ChangeToUniCodeFont();
	}
	else
	{
		//FIGApp::ChangeToEnglishFont();
	}

	
	

    //FontManager::Instance().Recreate();
	//ui::UIManager::Instance().RefreshText();
//#else

    
	
//#endif
#ifdef _PLATFORM_IOS
    if(GetWidget("button_highscore"))
		GetWidget("button_highscore")->SetPosition((math::Vec2(3.0f,3.0f)));
    
	if(GetWidget("button_achievements"))
		GetWidget("button_achievements")->SetPosition((math::Vec2(3.0f,3.0f)));
#endif

	FIGBoneFileCache::Instance().ReadSingleFile("transform/title.lua");
	m_BoneTitle.Load("transform/title.lua");

	GetWidget("title_number2")->SetIsVisible(false);

	ui::UIFlexEffect* pFlexEffect = (ui::UIFlexEffect*)GetWidget("animation");
	pFlexEffect->SetRenderFunc((ui::UIFlexEffect::FLEXEFFECT_RENDERFUNCTION) RenderAnimation);

	//m_BoneTitle.Tick(0);

	m_pUI = GetWidget("main_menu");
}




bool	FIGMainMenu::OnEnter()
{
	/*
	FIGSFXManager::Instance().Clear();

	// random twikle ^_^ 
	const int TWINKLE_C = 10;
	FIGSfx::SFX_TYPES Sfx_type;
	math::Vec2 Pos;
	for( int i = 0; i < TWINKLE_C; i++)
	{
		
		if( i % 2 == 0)
			Sfx_type = FIGSfx::TWINKLE1;
		else
			Sfx_type = FIGSfx::TWINKLE2;

		Pos = math::Vec2( num::RAND32::Instance().RandFloat(0,1.0f),		 
						  num::RAND32::Instance().RandFloat(0,1.0f)
						  );
		FIGSFXManager::Instance().Spawn(
									Sfx_type, 
									Pos,
									Fighter::Instance().GetScale()
									);
	}
	
	// random space dust ^_^
   const int SPACE_DUST_C = 10;
	for( int i = 0; i < SPACE_DUST_C; i++)
	{
		Pos = math::Vec2( num::RAND32::Instance().RandFloat(0,1.0f),		 
						  num::RAND32::Instance().RandFloat(0,1.0f)
						  );
		FIGSFXManager::Instance().Spawn(
									FIGSfx::SPACE_DUST, 
									Pos,
									Fighter::Instance().GetScale()
									);
	}
	*/
	if(g_pApp && g_pApp->GetRMS())
	{
		AUDIO().SetSFXVolume((int)g_pApp->GetRMS()->GetSoundVolume());
		AUDIO().SetMusicVolume((int)g_pApp->GetRMS()->GetMusicVolume());
	}

	

	return FIGMOGAUIState::OnEnter();
}
bool	FIGMainMenu::OnExit()
{
	
	FIGSFXManager::Instance().Clear(); 
	MATUIAnimator::Instance().Clear();
	return FIGMOGAUIState::OnExit();
}



bool	FIGMainMenu::Tick(float dt)
{
	//FIGSFXManager::Instance().Tick(dt);
	//FIGMovingParticles::Instance().Tick(dt);
	//m_MainSpaceBG.Tick(dt);

	if( dt == 0)
	{
#if defined(_PLATFORM_IOS) || defined (_PLATFORM_ANDROID)
	dt = 1.0f / 30.0f;
#else
	dt = 1.0f / 60.0f;
#endif  
		
	}

	m_BoneTitle.SetPos(math::Vec2(0.5f,0.24f));
	m_BoneTitle.SetRotation(0);
	m_BoneTitle.Tick(dt);

	if(!m_IsFinishTitleAnimation)
	{
		if( m_BoneTitle.TransformForwardTick(dt))
		{
			MATUIAnimator::Instance().Add(GetWidget("title_number2"),MATAnimatedUI::ANIMATE_STYLE_STAMP,0.1f,this);
			m_IsFinishTitleAnimation = true;			
		}
		
	}

	MATUIAnimator::Instance().Tick(dt);
	FIGUIPopupAnimatorMgr::Instance().Tick(dt);
	m_ShakeScreen.Tick(dt);

		
	return FIGMOGAUIState::Tick(dt);

} 


void	FIGMainMenu::OnAnimatedUIFinish()
{
	m_ShakeScreen.Shake(1.1f);	
}


bool	FIGMainMenu::PreRender()
{
	
	if(m_pUI)
	{
		m_pUI->SetPosition( m_ShakeScreen.m_CurrentShakeOffset);
	}

	bool b = true;
	b = FIGMOGAUIState::PreRender();
	
	return b;
}

bool		FIGMainMenu::PostRender()
{	
	bool b = true;
	b = FIGMOGAUIState::PostRender();
#ifdef _DEMOVERSION
	FontManager::Instance().PrintCentered(math::Vec2(0.5f,0.92f), "Demo Version/not to publish");
#endif

	

	return b;
}

void		FIGMainMenu::KeyPressed(input::Keyboard::KEY* pKey)
{
	_LOG(MSG_COMMENT,"Key pressed");
	if(pKey->KeyID == KEY_ESCAPE)
	{
		PressedEsc();			
	}
	else
	{
		
	}
	FIGMOGAUIState::KeyPressed(pKey);
}

void					FIGMainMenu::PressedEsc()
{
	gameflow::UIPopup* pPopup = gameflow::UIPopupManager::Instance().GetPopup("ui/settings.ui");
	if(pPopup && pPopup->IsActive())
	{

	}
	else
	{	
		
		gameflow::UIPopupManager::Instance().StartYesNo("", UI_DELEGATE(FIGMainMenu, OnHardQuit), UI_DELEGATE(FIGMainMenu, OnQuitNo));
		FIGUIPopupAnimator* pPopup = FIGUIPopupAnimatorMgr::Instance().Show(FIGUIPopupAnimatorMgr::POPUP_NAMES_YESNO);		
		pPopup->GetPopup()->GetWidget("YesNoText")->SetOffImage("question_quit");
		ui::UIManager::Instance().Tick(0);
	}	
}

void DELEGATE_CALL		FIGMainMenu::OnButtonLeaderBoard(ui::UIWidget::WIDGET_EVENT Event, ui::UIWidget* pWidget)
{
// more games // facebook
#ifdef _PLATFORM_IOS
    FIGIOSWrapper::Instance().FIG_GotoWebSite("http://facebook.com/2dstar");
    // loading gamecenter
	//FIGGameCenter::Instance()->ShowLeaderBoard();
#endif

#ifdef _PLATFORM_ANDROID
	Android_JNI_SendMessage(FUNC_gotoURL, 1);
#endif
    
}

void DELEGATE_CALL		FIGMainMenu::OnButtonAchievements(ui::UIWidget::WIDGET_EVENT Event, ui::UIWidget* pWidget)
{
    
    // rate us
#ifdef _PLATFORM_IOS
    FIGIOSWrapper::Instance().FIG_GotoWebSite(FIGConstants::ITUNE_LINK);
    // loading gamecenter
	//FIGGameCenter::Instance()->ShowAchievements();
#endif

#ifdef _PLATFORM_ANDROID
	Android_JNI_SendMessage(FUNC_gotoURL, 0);
#endif
    
}

void DELEGATE_CALL		FIGMainMenu::OnButtonSettings(ui::UIWidget::WIDGET_EVENT Event, ui::UIWidget* pWidget)
{
	FIGUIPopupAnimatorMgr::Instance().Show(FIGUIPopupAnimatorMgr::POPUP_NAMES_SETTING);
}

void DELEGATE_CALL		FIGMainMenu::OnHardQuit(ui::UIWidget::WIDGET_EVENT Event, ui::UIWidget* pWidget)
{

	if(g_pApp && g_pApp->GetHandler())
		g_pApp->GetHandler()->DestroyWindow();

#ifdef _PLATFORM_ANDROID
	Android_JNI_SendMessage(FUNC_onHardQuit, 0);
#endif

}

void DELEGATE_CALL		FIGMainMenu::OnQuitNo(ui::UIWidget::WIDGET_EVENT Event, ui::UIWidget* pWidget)
{

}

bool	FIGMainMenu::OnUIKeyDownEvent(int	KeyCode)
{
	_LOG(MSG_COMMENT, "mainmenu key down");
	if(FIGUIPopupAnimatorMgr::Instance().OnUIKeyDownEvent(KeyCode))
	{
		_LOG(MSG_COMMENT, "mainmenu key down popup taken");
		// taken
		return true;
	}

	switch( (input::MOGAJoystick::KEYCODE)KeyCode)
	{
		case input::MOGAJoystick::KEYCODE_BUTTON_B:				
			PressedEsc();
		break;
		
		
	}

	return FIGMOGAUIState::OnUIKeyDownEvent(KeyCode);
}
